from django.shortcuts import render
from django.views import View
from apps.verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
import random, logging
from apps.verifications.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import ccp_send_sms_code

# Create your views here.

logger = logging.getLogger('django')


class ImageCodeView(View):
    """图形验证码"""
    def get(self, request, uuid):
        """实现图形验证码逻辑"""
        # 生成图形验证码
        text, image = captcha.generate_captcha()
        # 保存图形验证码
        # 使用配置的redis数据库别名,创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        # 响应图形验证码
        return http.HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 提取绑定至手机号的标记,来验证是否频繁发送短信验证码
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 判断标记是否存在,若已存在,响应错误信息,终止程序逻辑
        if send_flag:
            return http.JsonResponse({'code': 400, 'errmsg': "请别频繁发送短信验证码"})

        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 提取图形验证码
        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s' % uuid)
        # 判断图形验证码是否过期
        if not image_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码过期'})
        # 删除图形验证码
        redis_conn.delete('img_%s' % uuid)
        # 对比图形验证码
        # 统一类型和大小写
        image_code_client = image_code_client.lower()
        image_code_server = image_code_server.decode().lower()
        if image_code_server != image_code_client:
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码不匹配'})

        # 生成短信验证码
        random_num = random.randint(0, 999999)
        sms_code = "%06d" % random_num
        # 写入验证码至日志
        logger.info(sms_code)
        # 保存短信验证码
        redis_conn = get_redis_connection('verify_code')
        # redis_conn.setex("sms_%s" % mobile, 300, sms_code)
        # 发送短信验证码时,给该手机号码添加标记
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        # 使用管道执行请求数据库的操作(利用redis事务原理)
        # 创建管道
        pl = redis_conn.pipeline()
        # 添加请求至管道
        pl.setex('sms_%s' % mobile, 300, sms_code)
        # 发送短信验证码时,给该手机号码添加标记
        pl.setex('send_flag_%s' % mobile, 60, 1)
        # 执行管道
        pl.execute()

        # 发送短信验证码:对接容联云通讯SDK
        # CCP().send_template_sms(mobile, [sms_code, 4], 1)
        # 使用celery的异步任务发送短信验证码
        ccp_send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '发送短信验证码成功'})